<template>
    <div style="width:100%"> 
        <el-form ref="baiFormRef" :model="businessDetail" label-width="110px">
          <el-form-item label="详细地址：" prop="address">
            <el-autocomplete v-model="businessDetail.address" style="width:100%;" popper-class="autoAddressClass"
              :fetch-suggestions="querySearchAsync" :trigger-on-focus="false" placeholder="详细地址" clearable
              @select="handleSelect">
              <template  #default="{ item}">
                <i class="el-icon-search fl mgr10" />
                <div style="overflow:hidden;">
                  <div class="title">{{ item.title }}</div>
                  <span class="address ellipsis">{{ item.address }}</span>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-form>
  
        <baidu-map class="bm-view" ak="3LgMlTyAIzk2ok2Sn5ZY6NPPmVQjMFch"   :center="mapData.center" :zoom="mapData.zoom"
          @ready="mapHandler" @click="getLocation">
          <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-map-type>
          <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
          <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
          <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
        </baidu-map>
  
        <el-row>
          <el-col :span="24" class="rt">
             <el-button type="primary" @click="chooseLocation">确定位置</el-button>
          </el-col>
        </el-row> 
    </div>
</template>

<script setup>
   import { ref, watch} from 'vue'
   import {  Plus } from '@element-plus/icons-vue'
   import { ElMessage  } from 'element-plus'
   import { BaiduMap, BmMarker, BmNavigation,BmGeolocation,BmCityList,BmControl,BmAutoComplete,BmMapType} from 'vue-baidu-map-3x'
   
   //vue3先要定义emit (官网定义)
   //const emit = defineEmits(['myclick'])
   
   // vue3中也可以使用代理来实现
    const { proxy } = getCurrentInstance(); 
    
   //暴露的属性
   const props = defineProps({
       itemData: {
           type: Object,
           default: () => {}
         }
   })
   
  //BMap类
  const BMap =ref(null)
  //地图对象
  const map =ref(null)
   
   const data=reactive({
     //商家信息(包含坐标信息)
      businessDetail: {
        address: undefined,
        latitude: undefined,
        longitude: undefined
      },
      mapData: {
        //中心坐标
        center: {
          lng: 0,
          lat: 0
        },
        //缩放级别
        zoom: 13
      }
   });
   
   const { businessDetail, mapData} = toRefs(data);
   
   // 初始化操作
   function init(){
     businessDetail.value.address=props.itemData.address
     businessDetail.value.latitude=props.itemData.latitude
     businessDetail.value.longitude=props.itemData.longitude
   }
 
  init()
  
  //地图异步初始化操作
   const mapHandler = async (result) => {
      console.log('======初始化----')
      //保存百度地图类
      BMap.value = result.BMap
      //保存地图对象
      map.value = result.map
     //如果一开始坐标存在(编辑的时候)
     if (props.itemData && props.itemData.address) {
        businessDetail.value.address=props.itemData.address
     }
     
     // 如果传过的参数有经度，有纬度，默认显示指定的位置
     if (props.itemData && props.itemData.longitude && props.itemData.latitude) {
       //设置坐标
       mapData.value.center.lng =businessDetail.value.longitude = props.itemData.longitude
       mapData.value.center.lat =businessDetail.value.latitude = props.itemData.latitude
     }else{
       mapData.value.center.lng = businessDetail.value.longitude = 106.472962
       mapData.value.center.lat = businessDetail.value.latitude = 29.631662       
     }
     
     //初始化坐标
      var point = new BMap.value.Point( businessDetail.value.longitude,  businessDetail.value.latitude); 
      
     //添加一个半径圆
     var circle = new BMap.value.Circle(point,5000,{fillColor:"blue", strokeWeight: 1 ,fillOpacity: 0.3, strokeOpacity: 0.3});
     map.value.addOverlay(circle);
     
     //添加一个点，让用户清楚知道你当前大概位置
     
     const marker = new BMap.value.Marker(point)
     //将标记添加到地图上
     map.value.addOverlay(marker)
     mapData.value.zoom= 13
   };
  
  
  //输入提示词的时候，回调结果 str，输入框的内容， cb你处理完以返回的结果发现是数组[]
  function querySearchAsync(str, cb){   
   // https://lbsyun.baidu.com/jsdemo.htm#localSearchKeyData   看文档
   var options = {
     onSearchComplete: function(res) { 
       var s = []
       if (local.getStatus() == BMAP_STATUS_SUCCESS) {
         for (var i = 0; i < res.getCurrentNumPois(); i++) { 
           s.push(res.getPoi(i))
         }
         cb(s)
       } else {
         cb(s)
       }
     }
   };
   
   //调用百度地图检索服务
   var local = new BMap.value.LocalSearch(map.value, options)
   //local.search(str) 
   //搜索离我最近5公里的内容   经度: businessDetail.value.longitude,  纬度:  businessDetail.value.latitude
    var mPoint = new BMap.value.Point(businessDetail.value.longitude, businessDetail.value.latitude); 
    local.searchNearby(str,mPoint,5000);
   //  local.searchNearby('餐馆',mPoint,1000);
   
  }
  
  //自动补全选中回调函数
  function handleSelect(item){     
    businessDetail.value.address = item.address + item.title
    //百度地图类
    let BMapGL = BMap.value
    //地图对象
    let mapTemp = map.value
    //清除地图上所有的覆盖物(保证每次点击只有一个标记)
    mapTemp.clearOverlays()
    
    var point=new BMapGL.Point(item.point.lng, item.point.lat);
    //添加一个半径圆
    var circle = new BMapGL.Circle(point,5000,{fillColor:"blue", strokeWeight: 1 ,fillOpacity: 0.3, strokeOpacity: 0.3});
    mapTemp.addOverlay(circle);
    
    //创建定位标记
    let marker = new BMapGL.Marker(point);
    //将标记添加到地图上
    mapTemp.addOverlay(marker)
      
    mapData.value.center.lng = businessDetail.value.longitude = item.point.lng
    mapData.value.center.lat = businessDetail.value.latitude = item.point.lat
  }
  
  //在地图上点击，查询当前的 位置返回数据
  function  getLocation(e) {
          console.log(e)
          //设置经度
         businessDetail.value.longitude = e.point.lng
          //设置纬度
          businessDetail.value.latitude = e.point.lat
          //百度地图类
          let BMapGL = BMap.value       
          //地图对象
          let mapTemp = map.value
          //清除地图上所有的覆盖物(保证每次点击只有一个标记)
          mapTemp.clearOverlays();
          //创建定位标记
          let marker = new BMapGL.Marker(new BMapGL.Point(e.point.lng, e.point.lat))
          //将标记添加到地图上
          mapTemp.addOverlay(marker)
          //创建坐标解析对象
          let geoc = new BMapGL.Geocoder()
          //解析当前的坐标成地址
          geoc.getLocation(e.point, (rs) => {
            console.log(rs)
            //获取地址对象
            let addressComp = rs.addressComponents
            //拼接出详细地址
            businessDetail.value.address =
              addressComp.province +
              addressComp.city +
              addressComp.district +
              addressComp.street +
              addressComp.streetNumber
          });
    }
  
   
   //确定选择坐标
   function  chooseLocation() { 
      
       if(businessDetail.value && businessDetail.value.address){
         // vue3的标准通知父组件        
        // emit('myclick',businessDetail.value)
        
        //代理方式
         proxy.$emit('myclick',businessDetail.value)
       }else{
          ElMessage({ message: '请先选择所在位置',type: 'error'})        
       }

   }
  
</script>


 
<style>
  
  .BMap_cpyCtrl {
    display: none;
  }
    
  .anchorBL {
    display: none;
  } 
  
  .bm-view {
    width: 100%;
    height: 90%;
  }

  .rt{
        text-align: right;
        padding-top: 20px;
  }
</style>
